package com.ljd.gulimall.ware.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ljd.common.constant.WareConstant;
import com.ljd.common.utils.R;
import com.ljd.gulimall.ware.entity.PurchaseDetailEntity;
import com.ljd.gulimall.ware.entity.WareSkuEntity;
import com.ljd.gulimall.ware.feign.ProductFeign;
import com.ljd.gulimall.ware.service.PurchaseDetailService;
import com.ljd.gulimall.ware.service.WareSkuService;
import com.ljd.gulimall.ware.vo.MergeVo;
import com.ljd.gulimall.ware.vo.PurchaseDoneVo;
import com.ljd.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljd.common.utils.PageUtils;
import com.ljd.common.utils.Query;

import com.ljd.gulimall.ware.dao.PurchaseDao;
import com.ljd.gulimall.ware.entity.PurchaseEntity;
import com.ljd.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;
    @Autowired
    ProductFeign productFeign;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByStatus(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().in("status",0,1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void merge(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if(purchaseId == null) {
            PurchaseEntity purchase = new PurchaseEntity();
            purchase.setUpdateTime(new Date());
            purchase.setCreateTime(new Date());
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchase);
            purchaseId = purchase.getId();
        }
        List<Long> items = vo.getItems();
        // 只有新建和已分配的状态才可以合并
        List<PurchaseDetailEntity> detailEntities = (List<PurchaseDetailEntity>) purchaseDetailService.listByIds(items);
        Long finalPurchaseId = purchaseId;
        detailEntities = detailEntities.stream().filter(purchaseDetailEntity -> Objects.equals(purchaseDetailEntity.getStatus(), WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())
        || Objects.equals(purchaseDetailEntity.getStatus(), WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()))
                .peek(purchaseDetailEntity -> {
                    purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                    purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(detailEntities);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(finalPurchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
        List<PurchaseEntity> purchaseEntities = (List<PurchaseEntity>) this.listByIds(ids);
        if(purchaseEntities == null || purchaseEntities.size() == 0) {
            return;
        }
        // 采购单变为已领取
        List<PurchaseEntity> purchaseEntityList = purchaseEntities.stream().filter(purchaseEntity -> Objects.equals(purchaseEntity.getStatus(), WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        || Objects.equals(purchaseEntity.getStatus(), WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()))
                .peek(purchaseEntity -> {
                    purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    purchaseEntity.setUpdateTime(new Date());
                }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntityList);
        // 采购项变为正在采购
        List<Long> itemIds = purchaseEntityList.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().in("purchase_id", itemIds));
        if(purchaseDetailEntities != null && purchaseDetailEntities.size() > 0) {
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().filter(purchaseDetailEntity -> Objects.equals(purchaseDetailEntity.getStatus(), WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())
                            || Objects.equals(purchaseDetailEntity.getStatus(), WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode()))
                    .peek(purchaseDetailEntity -> purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode())).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }


    }

    @Transactional
    @Override
    public void purchaseDone(PurchaseDoneVo vo) {
        Long id = vo.getId();
        if(id == null) {
            return;
        }
        List<PurchaseItemDoneVo> items = vo.getItems();

        // 采购完成的采购需求要加库存
        List<PurchaseItemDoneVo> finishItems = items.stream().filter(vo1 -> Objects.equals(vo1.getStatus(), WareConstant.PurchaseDetailStatusEnum.FINISH.getCode()))
                .collect(Collectors.toList());
        if(finishItems.size() > 0) {
            List<Long> detailIds = finishItems.stream().map(PurchaseItemDoneVo::getItemId).collect(Collectors.toList());
            List<PurchaseDetailEntity> detailEntities = (List<PurchaseDetailEntity>) purchaseDetailService.listByIds(detailIds);
            // 加库存
            for (PurchaseDetailEntity detailEntity : detailEntities) {
                Long skuId = detailEntity.getSkuId();
                Long wareId = detailEntity.getWareId();
                Integer skuNum = detailEntity.getSkuNum();
                List<WareSkuEntity> skuEntities = wareSkuService.list(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
                if(skuEntities == null || skuEntities.size() ==0) {
                    // 新增
                    WareSkuEntity wareSkuEntity = new WareSkuEntity();
                    wareSkuEntity.setSkuId(skuId);
                    wareSkuEntity.setWareId(wareId);
                    wareSkuEntity.setStock(skuNum);
                    wareSkuEntity.setStockLocked(0);
                    try {
                        R r = productFeign.SkuInfo(skuId);
                        if(r.getCode() ==0) {
                            Map<String, Object> skuInfo = (Map<String, Object>) r.get("skuInfo");
                            Object skuName = skuInfo.get("skuName");
                            wareSkuEntity.setSkuName((String) skuName);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    wareSkuService.save(wareSkuEntity);
                } else {
                    WareSkuEntity skuEntity = skuEntities.get(0);
                    wareSkuService.updateSku(skuEntity.getId(), skuNum);
                }
            }
            // 改状态
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(en -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                entity.setId(en.getId());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        }
        // 未采购完成的改状态
        List<PurchaseItemDoneVo> noFinishItems = items.stream().filter(vo1 -> Objects.equals(vo1.getStatus(), WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()))
                .collect(Collectors.toList());
        if(noFinishItems.size() > 0) {
            List<PurchaseDetailEntity> collect = noFinishItems.stream().map(en -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(en.getItemId());
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
                return entity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
            // 存在未采购完成的采购需求，采购单状态未采购失败，否则采购完成
            PurchaseEntity entity = new PurchaseEntity();
            entity.setId(id);
            entity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
            entity.setUpdateTime(new Date());
            this.updateById(entity);
        } else {
            PurchaseEntity entity = new PurchaseEntity();
            entity.setId(id);
            entity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
            entity.setUpdateTime(new Date());
            this.updateById(entity);
        }

    }

}